import { useDeviceMode } from "@/hooks/useDeviceMode";
import { PrismaClient } from "@prisma/client";
import styles from "@/styles/home.module.scss";
import { useRef, useState } from "react";
import { useRouter } from "next/router";
import Head from "next/head";
import { get } from "@/utils/_";
import Cookies from "cookies";
import ConfirmModal from "@/components/ConfirmModal";
interface ArticleItem {
  title: string;
  id: string;
  user: { name: string; id: string };
  tags: { name: string; id: number; color: string; background: string }[];
}

interface HomePageProps {
  top10: ArticleItem[];
}

export default function Home(props: HomePageProps) {
  const router = useRouter();
  const mobile = useDeviceMode();
  const [userinput, setUserinput] = useState("");

  const handleClickProxy = (e: any) => {
    const element = e.nativeEvent.target.closest(
      "div[data-id]"
    ) as HTMLElement | null;
    if (element) {
      const id = element.getAttribute("data-id");
      if (id) {
        router.push(`/article/${id}`);
      }
    }
  };

  return (
    <>
      <div
        className={"flex flex-col items-center pt-40 box-border"}
        style={{
          height: "calc(100vh - 64px)",
        }}
      >
        <Head>
          <title>主页</title>
          <meta
            name={"keywords"}
            content={props.top10[0]?.title || "aursor life aursor"}
          ></meta>
          <meta
            name={"description"}
            content={props.top10[1]?.title || "aursor life aursor"}
          ></meta>
        </Head>
        <h3 className={styles.title}>Aursor Life</h3>
        <div className={mobile ? styles.searchMobile : styles.search}>
          <input
            type="text"
            className={styles["input"]}
            placeholder="我想找一篇文章,会在这里输入标题关键字~"
            value={userinput}
            onKeyDown={(e) => {
              if (e.key.toLowerCase() === "enter") {
                router.push(`/search?q=${userinput}`);
              }
            }}
            onChange={(e) => {
              setUserinput(e.target.value);
            }}
          />
        </div>
        <div
          className={mobile ? styles.top10Mobile : styles.top10}
          onClick={handleClickProxy}
        >
          {props.top10.map((item) => (
            <div className={styles["top-item"]} data-id={item.id} key={item.id}>
              <div
                className={styles["top10-tag"]}
                style={{
                  color: get(item, "tags[0].color"),
                  background: get(item, "tags[0].background"),
                }}
              >
                {get(item, "tags[0].name")}
              </div>
              <span>{item.title}</span>
            </div>
          ))}
        </div>
        <div
          className="flex justify-center items-center cursor-pointer"
          style={{ color: "#49e" }}
          onClick={() => {
            router.push("/search");
          }}
        >
          MORE&gt;
        </div>
      </div>
    </>
  );
}

export async function getServerSideProps({ req, res }: { req: any; res: any }) {
  const prisma = new PrismaClient();
  const cookier = new Cookies(req, res);
  const userEncoded = decodeURIComponent(
    decodeURIComponent(cookier.get("user") as string)
  );
  const top10 = await prisma.article.findMany({
    skip: 0,
    take: 5,
    where: {
      OR: [{ public: true }, { userId: JSON.parse(userEncoded).id }],
    },
    orderBy: {
      createdAt: "desc",
    },
    select: {
      title: true,
      id: true,
      tags: {
        select: {
          name: true,
          id: true,
          color: true,
          background: true,
        },
      },
      user: {
        select: {
          name: true,
          id: true,
        },
      },

      createdAt: false,
      updatedAt: false,
    },
  });

  return {
    props: {
      top10,
    },
  };
}
